<script>
import { defineComponent, onMounted, onUnmounted, reactive, toRefs } from "vue";
import hlsjs from "hls.js";
import {
  apiPrintScreen,
  apiRecordingStart,
  apiRecordingStop,
} from "../api/preview.js";
import { apiFilter } from "../api/file.js";
import { dateFormat } from "../utils/date.js";
import { ElNotification } from "element-plus";
import { Delete, Download, Search } from "@element-plus/icons-vue";
import { useUserStore } from "@/store/modules/user.js";
import { getConfigList } from "@/api/configure.js";

export default defineComponent({
  name: "ComPreview",
  props: {
    cors: {
      type: Boolean,
      default: null,
    },
    autoCleanupMinBackwardDuration: {
      type: Boolean,
      default: null,
    },
    withCredentials: {
      type: Boolean,
      default: null,
    },
    enableWorker: {
      type: Boolean,
      default: null,
    },
    enableStashBuffer: {
      type: Boolean,
      default: null,
    },
    stashInitialSize: {
      type: Number,
      default: 384,
    },
    autoCleanupSourceBuffer: {
      type: Boolean,
      default: true,
    },
    hasPlayControl: {
      type: Boolean,
      default: false,
    },
    hasPrintScreen: {
      type: Boolean,
      default: false,
    },
    hasRecording: {
      type: Boolean,
      default: false,
    },
    hasSetting: {
      type: Boolean,
      default: false,
    },
    hasDownload: {
      type: Boolean,
      default: false,
    },
  },
  setup(prop, { emit }) {
    const state = reactive({
      flvPlayer: null,
      isRecording: false,
      downLoadDialogVisible: false,
      queryForm: {
        fileType: 0,
        endTime: null,
        startTime: null,
      },
      fileList: [],
      player: "",
      rtsp: "",
      hls: null,
      recordId: "",
      ipAddress: "",
      videosrc: "",
    });

    const store = useUserStore();

    // const webrtcPlay = () => {
    //   if (flvjs.isSupported()) {
    //     // if (state.flvPlayer) {
    //     //   state.flvPlayer.pause();
    //     //   state.flvPlayer.unload();
    //     //   state.flvPlayer.detachMediaElement();
    //     //   state.flvPlayer.destroy();
    //     // }
    //     state.flvPlayer = flvjs.createPlayer(
    //       {
    //         type: "flv",
    //         // type: "mp4",
    //         // url: "http://103.242.175.243:10000/sms/34020000002020000001/flv/hls/34020000001320000001_34020000001320000001.flv",
    //         // url: "ws://103.242.175.243:10000/sms/34020000002020000001/ws-flv/hls/34020000001320000001_34020000001320000001.flv",
    //         // url: "http://localhost:8888/stream",
    //         url: "http://localhost:8888/stream/index.m3u8",
    //         hasAudio: false, //是否包含音频
    //         hasVideo: true, //是否包含视频
    //         isLive: true, //是否是直播流
    //         enableStashBuffer: true, //是否启用缓冲区
    //         cors: true, // 是否跨域
    //       },
    //       {
    //         enableWorker: false, //  不启用分离线程
    //         enableStashBuffer: false, //  关闭IO隐藏缓冲区
    //         autoCleanupSourceBuffer: true, //自动清除缓存
    //       }
    //     );
    //     state.flvPlayer.attachMediaElement(
    //       document.querySelector("#myVideoFlv")
    //     ); // 在这里绑定元素
    //     state.flvPlayer.load();
    //     state.flvPlayer.play();
    //     state.flvPlayer.on(flvjs.Events.ERROR, (errType, errDetail) => {
    //       console.log("errType:", errType);
    //       console.log("errorDetail:", errDetail);
    //       if (state.flvPlayer) {
    //         destroyVideo();
    //         // webrtcPlay();
    //       }
    //     });
    //   }
    // };

    //挂载，播放
    onMounted(() => {
      // initList();
      // usePreview();

      getConfigList(0).then((res) => {
        state.ipAddress = res.data.configNetworkTCPIP.deviceIpv4Addr;
        // http://127.0.0.1:8889/stream
        let src = "http://" + state.ipAddress + ":8889/stream";
        state.videosrc = src;

        // hlsPlay();
      });

      // getRTSPStream();
    });

    //卸载，销毁
    onUnmounted(() => {
      if (state.hls) {
        state.hls.destroy();
      }
      handleRecordingStop();
    });

    //播放hls流
    const hlsPlay = () => {
      if (hlsjs.isSupported()) {
        const video = document.querySelector("#myVideoFlv");
        state.hls = new hlsjs();
        // state.hls.config['autoStartLoad'] = true
        // state.hls.config['startFragPrefetch'] = true
        state.hls.config["maxBufferLength"] = 10;
        // state.hls.config["minBufferLength"] = 3;
        // state.hls.config["maxLoadingDelay"] = 3;
        state.hls.config.maxBufferSize = 10 * 1024 * 1024;
        state.hls.config.retry = {
          retries: 5, // 尝试重试次数
          backoff: "exponential", // 重试间隔策略
          maxRetryDelay: 5, // 最大重试延迟（秒）
        };
        let src = "http://" + state.ipAddress + ":8888/stream/index.m3u8";
        // const src = 'http://103.242.175.243:10000/sms/34020000002020000001/hls/34020000001320000001_34020000001320000001/live.m3u8'

        state.hls.on(hlsjs.Events.MANIFEST_PARSED, () => {
          video.play();
        });
        state.hls.on(hlsjs.Events.ERROR, (event, data) => {
          if (data.fatal) {
            switch (data.type) {
              case hlsjs.ErrorTypes.NETWORK_ERROR:
                break;
              case hlsjs.ErrorTypes.MEDIA_ERROR:
                state.hls.swapAudioCodec();
                state.hls.recoverMediaError();
                break;
              default:
                break;
            }
          }
        });
        state.hls.on(hlsjs.Events.LEVEL_SWITCHED, (event, data) => {
          console.log("level switch：", data.level);
          state.hls.startLoad();
        });
        state.hls.on(hlsjs.Events.BUFFER_FLUSHING, (event, data) => {
          console.log(data);
        });
        state.hls.on(hlsjs.Events.MEDIA_ATTACHED, () => {});
        state.hls.on(hlsjs.Events.BUFFER_APPENDED, () => {});
        state.hls.attachMedia(video);
        state.hls.loadSource(src);
        // video.addEventListener('timeupdate', () => {
        //   if (video.paused || video.ended) return
        //   if (video.currentTime + 2 < video.buffered.end(0)) {
        //     state.hls.destroy()
        //     state.hls = new hlsjs()
        //     state.hls.loadSource(src)
        //     state.hls.attachMedia(video)
        //   }
        // })
      }
    };

    const initList = () => {
      apiFilter(
        state.queryForm.fileType,
        state.queryForm.startTime || "",
        state.queryForm.endTime || ""
      ).then((res) => {
        state.fileList = res.data;
      });
    };

    //暂停
    const handleStop = () => {
      const video = document.querySelector("#myVideoFlv");
      video.pause();
    };
    //播放
    const handleStart = () => {
      const video = document.querySelector("#myVideoFlv");
      video.play();
    };

    //截图
    const handlePrintScreen = () => {
      ElNotification({
        title: "开始抓取",
        position: "bottom-right",
      });
      apiPrintScreen()
        .then((res) => {
          ElNotification({
            title: "抓取成功",
            message: res.data,
            position: "bottom-right",
          });
        })
        .catch((e) => {
          ElNotification({
            title: "抓取失败",
            message: e.message,
            position: "bottom-right",
          });
        });
    };

    //开始录制
    const handleRecordingStart = () => {
      if (!state.isRecording) {
        state.isRecording = true;
        ElNotification({
          title: "开始录制",
          position: "bottom-right",
        });

        apiRecordingStart()
          .then((res) => {
            state.recordId = res.data;
          })
          .catch((e) => {
            ElNotification({
              title: "开始录制失败",
              message: e.message,
              position: "bottom-right",
            });
          });
      }
    };

    //介绍录制
    const handleRecordingStop = () => {
      if (state.isRecording) {
        apiRecordingStop(state.recordId)
          .then((res) => {
            ElNotification({
              title: "录制成功",
              message: res.data,
              position: "bottom-right",
            });
            state.recordId = "";
          })
          .catch((e) => {
            ElNotification({
              title: "录制失败",
              message: e.message,
              position: "bottom-right",
            });
            state.recordId = "";
          })
          .finally(() => {
            state.isRecording = false;
          });
      }
    };

    const handleOpenDownload = () => {
      state.downLoadDialogVisible = true;
    };

    const handleFileSearch = () => {
      initList();
    };

    // const getVideo = () => {
    //   let canvas = document.getElementById("jsmpeg-canvas");
    //   let url = "ws://127.0.0.1:8999";

    //   // let arr = state.rtsp.split(":");
    //   // let url = "ws:" + arr[1] + ":8999";

    //   let options = {
    //     canvas: canvas,
    //   };
    //   state.player = new JSMpeg.Player(url, options);
    // };

    // const getRTSPStream = () => {
    //   apiGetRtspUrl().then((res) => {
    //     state.rtsp = res.data;
    //     // getVideo();
    //   });
    // };

    return {
      ...toRefs(state),
      Search,
      Download,
      Delete,
      dateFormat,

      handleStop,
      handleStart,
      handlePrintScreen,
      handleRecordingStart,
      handleRecordingStop,
      handleOpenDownload,
      handleFileSearch,
      // getVideo,
      // getRTSPStream,
    };
  },
});
</script>

<template>
  <div class="component-com-preview-container">
    <!-- <canvas id="jsmpeg-canvas" class="video-meaner"></canvas> -->
    <!-- <video id="myVideoFlv" autoplay class="video-meaner" muted></video> -->
    <iframe :src="videosrc" class="video-meaner" frameborder="0" allowfullscreen></iframe>
    <div class="control-bar">
      <!-- <span v-if="hasPlayControl" class="btn-icon" @click="handleStop"
        >停止</span
      > -->
      <!-- <span v-if="hasPlayControl" class="btn-icon" @click="handleStart"
        >播放</span
      > -->
      <span v-if="hasPrintScreen" class="btn-icon" @click="handlePrintScreen"
        >截图</span
      >
      <span v-if="hasRecording" class="btn-icon" @click="handleRecordingStart"
        >录制</span
      >
      <span v-if="hasRecording" class="btn-icon" @click="handleRecordingStop"
        >结束</span
      >
      <span v-if="hasSetting" class="btn-icon">设置</span>
      <span v-if="hasDownload" class="btn-icon" @click="handleOpenDownload"
        >下载</span
      >
    </div>
    <el-dialog v-model="downLoadDialogVisible" :width="960" title="下载">
      <div class="dialog-download-container">
        <div class="download-filter-box">
          <div class="filter-header">查询条件</div>
          <div class="form-bound">
            <el-form label-position="top">
              <el-form-item label="文件类型">
                <el-select v-model="queryForm.fileType">
                  <el-option :value="0" label="录制文件" />
                  <el-option :value="1" label="定时文件" />
                </el-select>
              </el-form-item>
              <el-form-item label="开始时间">
                <el-date-picker
                  v-model="queryForm.startTime"
                  format="YYYY/MM/DD HH:mm:ss"
                  style="width: 100%"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
              <el-form-item label="结束时间">
                <el-date-picker
                  v-model="queryForm.endTime"
                  format="YYYY/MM/DD HH:mm:ss"
                  style="width: 100%"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
            </el-form>
            <el-button
              :icon="Search"
              style="width: 100%; background-color: #fe6266"
              type="primary"
              @click="handleFileSearch"
              >查找
            </el-button>
          </div>
        </div>
        <div class="download-file-box">
          <div class="file-header">
            <span>文件列表</span>
            <div class="button-group">
              <el-button :icon="Download" size="small">下载</el-button>
              <el-button :icon="Delete" size="small">删除</el-button>
            </div>
          </div>
          <div class="file-bound">
            <el-table :data="fileList" :max-height="536">
              <el-table-column type="selection" />
              <el-table-column
                :width="85"
                label="序号"
                show-overflow-tooltip
                type="index"
              />
              <el-table-column
                label="文件名"
                prop="fileName"
                show-overflow-tooltip
              />
              <el-table-column label="开始时间" show-overflow-tooltip>
                <template #default="scope">
                  <span>{{
                    dateFormat("yyyy-MM-dd hh:mm:ss", scope.row["startTime"])
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column label="结束时间" show-overflow-tooltip>
                <template #default="scope">
                  <span>{{
                    dateFormat("yyyy-MM-dd hh:mm:ss", scope.row["endTime"])
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="文件大小"
                prop="fileSize"
                show-overflow-tooltip
              />
              <el-table-column label="下载进度" show-overflow-tooltip />
            </el-table>
          </div>
          <div class="file-footer"></div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss">
.component-com-preview-container {
  height: 100%;

  .control-bar {
    height: 32px;
    background-color: #f2f2f2;
    color: #101010;
    padding: 0 20px;
    display: flex;
    align-items: center;
    justify-content: flex-end;

    .btn-icon {
      margin-left: 8px;
      font-size: 12px;
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;
      cursor: pointer;
    }
  }

  .video-meaner {
    width: 100%;
    height: calc(100% - 36px);

    /* 全屏按钮 */
    &::-webkit-media-controls-fullscreen-button {
      display: none;
    }

    /* 播放按钮 */
    &::-webkit-media-controls-play-button {
      display: none;
    }

    /* 进度条 */
    &::-webkit-media-controls-timeline {
      display: none;
    }

    /* 观看的当前时间 */
    &::-webkit-media-controls-current-time-display {
      display: none;
    }

    /* 剩余时间 */
    &::-webkit-media-controls-time-remaining-display {
      display: none;
    }

    /* 音量按钮 */
    &::-webkit-media-controls-mute-button {
      display: none;
    }

    /* 音量控制条 */
    &::-webkit-media-controls-volume-slider {
      display: none;
    }

    /* 所有控件 */
    &::-webkit-media-controls-enclosure {
      display: none;
    }

    // 如果不生效，加！important;
  }

  .el-dialog {
    padding: 8px;

    .el-dialog__header.show-close {
      padding-bottom: 4px;
    }

    .dialog-download-container {
      height: 600px;
      display: flex;

      .download-filter-box {
        width: 300px;
        height: 100%;

        .filter-header {
          height: 32px;
          background-color: #e6e6e6;
          color: #696969;
          font-weight: 600;
          padding-left: 8px;
          display: flex;
          align-items: center;
          justify-content: space-between;
        }

        .form-bound {
          padding: 12px;
        }
      }

      .download-file-box {
        width: calc(100% - 300px);
        height: 100%;
        border: 1px solid #afafaf;

        .file-header {
          height: 32px;
          background-color: #e6e6e6;
          color: #696969;
          font-weight: 600;
          padding: 0 8px;
          display: flex;
          align-items: center;
          justify-content: space-between;

          .button-group {
            display: flex;
            align-items: center;
            justify-content: center;
          }
        }

        .file-bound {
          height: 536px;
        }

        .file-footer {
          height: 32px;
          background-color: #e6e6e6;
        }
      }
    }
  }
}
</style>
